package com.ytjj.qmyx.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.qmyx.mall.mapper.FrontCategoryDao;
import com.ytjj.qmyx.mall.mapper.FrontCategoryMapper;
import com.ytjj.qmyx.mall.mapper.ProductDao;
import com.ytjj.qmyx.mall.model.FrontCategory;
import com.ytjj.qmyx.mall.model.Product;
import com.ytjj.qmyx.mall.model.request.ProductListRequest;
import com.ytjj.qmyx.mall.model.response.FrontCategoryResponse;
import com.ytjj.qmyx.mall.model.response.ProductCategoryResp;
import com.ytjj.qmyx.mall.service.FrontCategoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

/**
 * 
 * 
 * @description:
 */
@Service
public class FrontCategoryServiceImpl implements FrontCategoryService {

    @Autowired
    FrontCategoryDao frontCategoryDao;

    @Autowired
    FrontCategoryMapper frontCategoryMapper;

    @Autowired
    ProductDao productDao;

    @Autowired
    ProductServiceImpl productServiceImpl;

    @Autowired
    RedisService redisService;

    @Override
    public List<FrontCategoryResponse> getFrontListByType(Integer status, Integer pid) {
        List<FrontCategoryResponse> list = frontCategoryDao.findList(status, pid);
        return list;
    }

    /**
     * 通过专区Id查找商品（多级分类的专区）
     *
     * @param specialId:
     * @param type:
     * @param dataType:
     * @param platformData:
     * @returns: java.util.List<com.ytjj.qmyx.mall.model.Product>
     * 
     */
    @Override
    public List<Product> getProductListByFrontId(Integer specialId, String type, String dataType, String platformData, Integer pageNum, Integer pageSize) {
        //通过专区id找专区信息
        FrontCategory frontCategory = frontCategoryMapper.selectByPrimaryKey(specialId);
        //获取分类id
        String categoryListStr = frontCategory.getCategoryList();
        if (StringUtils.isEmpty(categoryListStr)) {
            return new ArrayList<>();
        }
        String[] split = categoryListStr.split(",");
        List<Integer> ids = new ArrayList<>();
        for (String s : split) {
            ids.add(Integer.valueOf(s));
        }
        //通过专区里的分类id获取到分类对象集合
        List<ProductCategoryResp> list = productDao.selectCategoryByIds(ids);
        //分类集合进行排序(三级放二级,二级放一级里)
        List<ProductCategoryResp> productCategoryResp = productServiceImpl.getProductCategoryResps(list);
        //获得层级关系的最后一级id
        List<Integer> categoryIds = productServiceImpl.getCategoryIds(productCategoryResp);
        if(categoryIds.size() == 0){
            return new ArrayList<Product>();
        }
        setProductIdToRedis(categoryIds, specialId, type, dataType, platformData);
        //分页获取
        PageHelper.startPage(pageNum, pageSize);
        List<Product> productList = productDao.getProductByCategoryIds(categoryIds, type, dataType, platformData);
        return productList;
    }





    /**
     * 通过专区Id找商品（好物推荐）
     *
     * @param specialId
     * @param dataType
     * @param activityTypeList
     * @return
     */
    public List<Product> getRecommendProductListByFrontId(Integer specialId, String dataType, List<String> activityTypeList, Integer pageNum, Integer pageSize) {
        //通过专区id找专区信息
        FrontCategory frontCategory = frontCategoryMapper.selectByPrimaryKey(specialId);
        //获取分类id
        String categoryListStr = frontCategory.getCategoryList();
        if (StringUtils.isEmpty(categoryListStr)) {
            return null;
        }
        String[] split = categoryListStr.split(",");
        List<Integer> ids = new ArrayList<>();
        for (String s : split) {
            ids.add(Integer.valueOf(s));
        }
        //通过专区里的分类id获取到分类对象集合
        List<ProductCategoryResp> list = productDao.selectCategoryByIds(ids);
        //分类集合进行排序(三级放二级,二级放一级里)
        List<ProductCategoryResp> productCategoryResp = productServiceImpl.getProductCategoryResps(list);
        List<Integer> categoryIds = productServiceImpl.getCategoryIds(productCategoryResp);
        if(CollectionUtils.isEmpty(categoryIds)){
            return new ArrayList<>();
        }
        //异步保存到redis
        setRecommendProductIdToRedis(categoryIds,specialId,dataType,activityTypeList);
        PageHelper.startPage(pageNum, pageSize);
        List<Product> productList = productDao.selectProductByThirdId(categoryIds, dataType, activityTypeList);
        return productList;
    }

    @Override
    public List<Product> getRecommendProductListByFrontId(Integer specialId, String dataType, List<String> activityTypeList, Integer pageNum, Integer pageSize, String platformData) {
        //通过专区id找专区信息
        FrontCategory frontCategory = frontCategoryMapper.selectByPrimaryKey(specialId);
        //获取分类id
        String categoryListStr = frontCategory.getCategoryList();
        if (StringUtils.isEmpty(categoryListStr)) {
            return null;
        }
        String[] split = categoryListStr.split(",");
        List<Integer> ids = new ArrayList<>();
        for (String s : split) {
            ids.add(Integer.valueOf(s));
        }
        //通过专区里的分类id获取到分类对象集合
        List<ProductCategoryResp> list = productDao.selectCategoryByIds(ids);
        //分类集合进行排序(三级放二级,二级放一级里)
        List<ProductCategoryResp> productCategoryResp = productServiceImpl.getProductCategoryResps(list);
        List<Integer> categoryIds = productServiceImpl.getCategoryIds(productCategoryResp);
        if(CollectionUtils.isEmpty(categoryIds)){
            return new ArrayList<>();
        }
        //异步保存到redis
        setRecommendProductIdAndPlatformDataToRedis(categoryIds,specialId,dataType,activityTypeList, platformData);
        PageHelper.startPage(pageNum, pageSize);
        List<Product> productList = productDao.selectProductByThirdIdAndPlatform(categoryIds, dataType, activityTypeList, platformData);
        return productList;
    }

    /**
     * 异步保存商品Id到redis
     *
     * @param categoryIds:
     * @param specialId:
     * @param type: 排序类型
     * @param dataType:
     * @param platformData:
     * @returns: java.util.concurrent.Future<java.lang.Boolean>
     * 
     */
    @Async
    public Future<List<Product>> setProductIdToRedis(List<Integer> categoryIds, Integer specialId, String type, String dataType, String platformData) {
        if(categoryIds.size() == 0){
            return new AsyncResult<>( new ArrayList<Product>());
        }
        List<Product> productList = productDao.getProductByCategoryIds(categoryIds, type, dataType, platformData);

        String id = "";
        for (Product product : productList) {
            id = id + "," + product.getId();
        }
        if(productList != null && productList.size() != 0){
            redisService.set("productsFromFrontCategoryIds:" + type + ":" + specialId, id);
            redisService.expire("productsFromFrontCategoryIds:" + type + ":" + specialId, 10 * 60);
        }
        return new AsyncResult<>(productList);

    }

    /**
    * 异步保存推荐商品Id到redis
    * @param categoryIds:
    * @param specialId:
    * @param dataType:
    * @param activityTypeList:
    * @returns: java.util.concurrent.Future<java.lang.Boolean>
    * 
    */
    @Async
    public Future<Boolean> setRecommendProductIdToRedis(List<Integer> categoryIds, Integer specialId,String dataType, List<String> activityTypeList) {

        List<Product> productList = productDao.selectProductByThirdId(categoryIds, dataType, activityTypeList);
        String id = "";
        for (Product product : productList) {
            id = id + "," + product.getId() ;
        }
        redisService.set("recommendProductsOfSpecial"+ ":" + specialId,id);
        redisService.expire("recommendProductsOfSpecial"+ ":" + specialId,10*60);

        return new AsyncResult<>(true);

    }

    @Async
    public Future<Boolean> setRecommendProductIdAndPlatformDataToRedis(List<Integer> categoryIds, Integer specialId,String dataType, List<String> activityTypeList, String platformData) {

        List<Product> productList = productDao.selectProductByThirdIdAndPlatform(categoryIds, dataType, activityTypeList, platformData);
        String id = "";
        for (Product product : productList) {
            id = id + "," + product.getId() ;
        }
        redisService.set("recommendProductsOfSpecial"+ ":" + specialId,id);
        redisService.expire("recommendProductsOfSpecial"+ ":" + specialId,10*60);

        return new AsyncResult<>(true);

    }


    /**
    * 根据类型分页获得专区商品
    * @param request:
    * @returns: java.util.List<com.ytjj.qmyx.mall.model.Product>
    * 
    */
    @Override
    public List<Product> getProductListForFrontCategory(ProductListRequest request) {
        List<Product> products = new ArrayList<>();
        if (redisService.get("productsFromFrontCategoryIds:" + request.getType() + ":" + request.getSpecialId()) == null) {
            //获取商品，并保存到redis
            products = getProductListByFrontId(request.getSpecialId(), request.getType(), TokenUtil.getDataType(), TokenUtil.getPlatformData(), request.getPageNum(), request.getPageSize());// 根据条件是会查出积分的,要求加以筛除
        } else {
            String s = redisService.get("productsFromFrontCategoryIds:" + request.getType() + ":" + request.getSpecialId());
            String[] split = s.split(",");
            List<Integer> id = new ArrayList<>();
            for (String s1 : split) {
                if (StringUtils.isNotEmpty(s1)) {
                    id.add(Integer.valueOf(s1));
                }
            }
            if (!CollectionUtils.isEmpty(id)) {
                Integer Num = (request.getPageNum() - 1) * request.getPageSize();
                products = productDao.getProductsOrderByType(id, Num, request.getType(), null);
            }
        }
        return products;
    }

}
